<!--
*  2021-03-15
*  余纱入库
-->
<template>
  <div id="app" class="yarn">
    <!-- 头部导航 -->
    <van-nav-bar
      left-arrow
      :title="params.stepName"
      left-text="重新扫码"
      @click-left="onClickLeft"
    >
      <!-- <template #left>
        <van-icon name="close" size="20" />
      </template> -->
    </van-nav-bar>
    <!-- 确认信息 -->
    <better-scroll
      class="public-scroll"
      :data="tableData"
      :totalPage="totalPage"
    >
      <van-cell-group>
        <van-cell>
          <template slot="title">
            <div class="yarn-cell">
              <span>系列</span>
              <span>颜色</span>
              <span>规格</span>
              <span>标重</span>
            </div>
          </template>
          <template slot="default">
            <span>操作</span>
          </template>
        </van-cell>
        <van-cell v-for="(data, index) in tableData" :key="index">
          <template slot="title">
            <div class="yarn-cell">
              <span>{{ data.yarnName }}</span>
              <span>{{ data.yarnNo }}</span>
              <span>{{ data.yarnStandard + "/" + data.yarnStrandNum }}</span>
              <span>{{ data.weight ? data.weight : 0 }}</span>
            </div>
          </template>
          <template slot="default">
            <van-button type="danger" @click="onClickCheckRes(data)"
              >打包</van-button
            >
          </template>
        </van-cell>
      </van-cell-group>
    </better-scroll>
    <van-button class="yarn-btn" @click="onGetNextInfo">确认</van-button>
    <van-dialog
      v-model="isLogin"
      title="确认重新扫码？"
      show-cancel-button
      confirm-button-text="重新扫码"
      @confirm="onClickBack"
    >
      <span>扫码后需重新登陆</span>
    </van-dialog>

    <!-- 打包 -->
    <van-popup
      v-model="showPopup"
      position="right"
      :style="{ width: '100%', height: '100%' }"
    >
      <yarn-list 
        :id="id"
        :yarnId="yarnId"
        :colorName="colorName"
        :yarnName="yarnName"
        :yarnStandard="yarnStandard"
        :yarnStrandNum="yarnStrandNum"
        :stdMoistureRegain="stdMoistureRegain"
        :params="params"
        :printMac="printMac"
        @onPrintData="onPrintData"
        @back="onBack"
      />
    </van-popup>
  </div>
</template>

<script>
import {
  getConfirmStep,
  getNextCommit,
  getNextInfo,
  getPublicData,
  getTaskAccept,
} from "@/api/warping";
import { getInit } from "@/api/login";
import { openWin } from "@/utils/index";
import YarnList from "./yarn-list/App";
import dayjs from "dayjs";
export default {
  name: "yarn",
  components: { YarnList },
  data() {
    return {
      tableData: [],
      nextStepData: [],
      nextStepAllData: [],
      params: {},
      show: false,
      radioGroup: [],
      radio: "5",
      resId: "",
      isShow: false,
      tableObj: {},
      demo: "",
      totalPage: 1,
      isLogin: false,
      result: [],
      doingResUrl: "",
      subResIds: [],
      showPopup: false,
      length: "",
      id: '',
      yarnId: '',
      colorName: '',
      yarnName: '',
      yarnStandard: '',
      yarnStrandNum: '',
      stdMoistureRegain: '',
      printMac: "",
      printStatus: false,
      printRow: {}
    };
  },
  watch: {
    // 监听打印机mac
    printMac(newVal) {
      if (newVal) {
        this.isEnabledBluetooth();
      }
    },
    // 监听打印状态
    printStatus(newVal) {
      if (newVal) {
        this.isEnabledBluetooth();
      }
    },
  },
  mounted() {
    const that = this;

    if (process.env.NODE_ENV === "production") {
      that.$nextTick(() => {
        that.params = window.api.pageParam;
        // 获取确认信息
        that.onGetConfirmStep();
        that.onGetInit();
        // 监听页面消失的时候，关掉页面就可以了
        window.api.addEventListener(
          {
            name: "viewdisappear",
          },
          function () {
            window.api.closeWin();
          }
        );
      });
    } else {
      window.apiready = () => {
        that.params = window.api.pageParam;
        console.log(that.params, "返回");
        // 获取确认信息
        that.onGetConfirmStep();
        that.onGetInit();
        // 监听页面消失的时候，关掉页面就可以了
        window.api.addEventListener(
          {
            name: "viewdisappear",
          },
          function () {
            window.api.closeWin();
          }
        );
      };
    }
  },
  methods: {
    // 重新扫码
    onClickLeft() {
      this.isLogin = true;
    },
    // 重新扫码
    onClickBack() {
      openWin("index");
    },
    // 打印初始化
    onGetInit() {
      this.printMac = "";
      getInit({}, (res) => {
        let resultArr = eval("(" + res.propertyValue + ")");
        resultArr.forEach((item) => {
          if (item.type == "1") {
            this.printMac = item.mac;
          }
        });
      });
    },

     // 查询蓝牙状态
    isEnabledBluetooth() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .isEnabledBluetooth({}, (ret, err) => {
          if (!err) {
            if (ret.state) {
              // 已打开
              that.getConnectState();
            } else {
              that.openBluetooth();
            }
          } else {
            that.$message.error("code: " + err.code + " msg: " + err.msg);
          }
        });
    },
    // 打开蓝牙
    openBluetooth() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .openBluetooth({}, function (ret, err) {
          if (!err) {
            if (ret.state) {
              // 已打开
              that.getConnectState();
            }
            
          } else {
            that.listenBluetoothStatus()
          }
        });
    },
    listenBluetoothStatus() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .listenBluetoothStatus({}, function (ret, err) {
          if (!err) {
            if (ret.status === 'STATE_ON') {
              that.getConnectState();
            }
          } else {
            that.$message.error("code: " + err.code + " msg: " + err.msg);
          }
        });
    },

    // 查询打印机连接状态
    getConnectState() {
      const that = this;
      that.$toast({
        type: "loading",
        message: "查询打印机连接状态",
        duration: 20000,
      });
      var obj = window.api.require("xGprinterPlus");
      var ret = obj.getConnectState();
      if (ret.status) {
        let result = false;
        ret.state.forEach((bool) => {
          if (bool) {
            result = bool;
          }
        });
        if (result) {
          // 已连接
          that.$toast.clear();
          that.$toast({
            type: "success",
            message: that.printStatus ? "已连接,正在打印" : "已连接",
            duration: 1500,
            onClose: () => {
              // 打印
              if (that.printStatus) {
                that.printLabel();
              }
            },
          });
        } else {
          // 未连接
          that.$toast.clear();
          that.$toast({
            type: "fail",
            message: "未连接, 请等待",
            duration: 1500,
            onClose: () => {
              that.connectBleByMacAddress();
            },
          });
        }
      } else {
        // 未连接
        that.$toast.clear();
        that.$toast({
          type: "fail",
          message: "未连接, 请等待",
          duration: 1500,
          onClose: () => {
            that.connectBleByMacAddress();
          },
        });
      }
    },
    // mac 地址连接
    connectBleByMacAddress() {
      const that = this;
      that.$toast({
        type: "loading",
        message: "初始化",
        duration: 20000,
      });
      var demo = window.api.require("xGprinterPlus");
      demo.connectBleByMacAddress(
        {
          macAddress:
            process.env.NODE_ENV === "production"
              ? that.printMac
              : "DC:1D:30:C6:58:8E",
        },
        function (ret, err) {
          if (ret.status) {
            if (ret.message === "已连接") {
              that.$toast.clear();
              that.$toast({
                type: "success",
                message: "连接成功",
                duration: 1500,
                onClose: () => {
                  if (that.printStatus) {
                    that.printLabel();
                  }
                },
              });
            } else if (ret.message === "连接失败") {
              that.$toast.clear();
              that.$toast({
                type: "fail",
                message: "初始化失败",
                duration: 1500,
              });
            }
          } else {
            that.$toast.clear();
            that.$toast.fail(err.msg);
          }
        }
      );
    },
    // 打印数据
    printLabel() {
      const that = this;
      var obj = window.api.require("xGprinterPlus");
      obj.printLabel(
        {
          rows: [
            {
              lineType: "size",
              width: 50,
              height: 70,
            },
            {
              lineType: "gap",
              data: 3,
            },
            {
              lineType: "cls",
            },
            {
              // 图片单元格竖线
              lineType: "bar",
              x: 25 + 130,
              y: 0,
              width: 2,
              height: 136,
            },
            {
              //绘制图片
              lineType: "image",
              x: 25 + 8,
              y: 8,
              data: "widget://image/huibo_logo.png",
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 8,
              y: 10,
              rotation: 0,
              xscal: 1,
              yscal: 1,
              data: "艺多染整",
            },
            {
              lineType: "qrcode", // 绘制qrcode
              x: 25 + 170 + 2,
              y: 10,
              level: "L", //L|M|H|Q
              cellwith: 5,
              rotation: 0, // 0|90|180|270
              data:
                "{" +
                "Id:" +
                "'" +
                that.printRow.id +
                "," +
                that.printRow.standardId +
                "'" +
                "}",
            },
            {
              // 横线
              lineType: "bar",
              x: 25 + 4,
              y: 136,
              width: 156,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 136 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: dayjs().format("YYYY-MM-DD"),
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 186,
              width: 608,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 186 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "品名：" + that.printRow.seriesName,
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 236,
              width: 608,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 236 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "颜色：" + that.printRow.colorName,
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 286,
              width: 608,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 286 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "规格：" + that.printRow.standardName,
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 336,
              width: 608,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 336 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "毛重：" + that.printRow.grossWeight,
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 386,
              width: 608,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 386 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "净重：" + that.printRow.netWeight,
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 436,
              width: 608,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 436 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "回潮: " + that.printRow.modulus,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 150 + 4,
              y: 436 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "筒只数: " + that.printRow.spindleNum,
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 486,
              width: 608,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 486 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "标重: " + that.printRow.weight,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 150 + 4,
              y: 486 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "筒只颜色: " + that.printRow.spindleColor,
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 536,
              width: 600,
              height: 2,
            },
            // {
            //   //绘制文本
            //   lineType: "text",
            //   x: 25 + 4,
            //   y: 506 + 2,
            //   rotation: 0,
            //   xscal: 1,
            //   yscal: 2,
            //   data: "日期: " + dayjs().format("YYYY-MM-DD"),
            // },
          ],
        },
        function (ret, err) {
          if (ret.status) {
            that.printStatus = false;
            that.$toast.success("打印成功");
          } else {
            that.$toast({
              type: "fail",
              message: err.code + err.msg,
              duration: 1500,
              onClose: () => {
                that.connectBleByMacAddress();
              },
            });
          }
        }
      );
    },
    // 改变打印状态
    onPrintData(data) {
      this.printRow = data
      this.printStatus = true
    },
    // 返回
    onBack(data) {
      this.printRow = {}
      this.printStatus = false
      this.showPopup = false
      if (data.refresh) {
        this.onGetConfirmStep()
      }
    },
    // 打包操作
    onClickCheckRes(data) {
      // openWin("yarn-list", {
      //   id: data.id,
      //   yarnId: data.yarnId,
      //   colorName: data.yarnNo,
      //   yarnName: data.yarnName,
      //   yarnStandard: data.yarnStandard,
      //   yarnStrandNum: data.yarnStrandNum,
      //   stdMoistureRegain: data.stdMoistureRegain,
      //   params: this.params,
      // });
      this.id = data.id.toString();
      this.yarnId = data.yarnId.toString();
      this.colorName = data.yarnNo;
      this.yarnName = data.yarnName;
      this.yarnStandard = data.yarnStandard.toString();
      this.yarnStrandNum = data.yarnStrandNum.toString();
      this.stdMoistureRegain = data.stdMoistureRegain;
      this.showPopup = true
    },
    // 获取确认信息
    onGetConfirmStep() {
      const that = this;
      let url =
        process.env.VUE_APP_YARN_URL +
        that.params.nextResUrl +
        "?planId=" +
        that.params.resId +
        "&type=2";
      getConfirmStep(
        {
          resUrl: url,
        },
        (res) => {
          console.log(res);
          that.tableData = res;
          let i = 0;
          let len = that.tableData.length;
          that.onGetLoopWeight(i, len);
        }
      );
    },
    // 循环获取重量
    onGetLoopWeight(i, len) {
      const that = this;
      getPublicData(
        {
          resUrl:
            process.env.VUE_APP_YARN_URL +
            this.params.resUrl +
            "?refType=11&refId=" +
            that.tableData[i].id,
        },
        (res) => {
          let totalWeight = 0;
          let packageIds = "";
          if (res instanceof Array) {
            res.forEach((item) => {
              totalWeight += Number(item.weight);
              packageIds += "," + item.id;
            });
          }
          that.tableData[i].weight = totalWeight;
          that.tableData[i].packageIds =
            packageIds !== "" ? packageIds.substr(1) : "";
          that.$forceUpdate();
          ++i;
          if (i < len) {
            that.onGetLoopWeight(i, len);
          }
        }
      );
    },
    // 获取下一步信息
    onGetNextInfo() {
      const that = this;
      that.nextStepData = [];
      that.nextStepAllData = [];
      // // 获取下一步信息
      getNextInfo(
        {
          flowType: that.params.flowType,
          stepNo: that.params.stepNo,
        },
        function (res) {
          that.nextStepAllData = res;
          // 胚布流程
          if (that.params.flowType === 3) {
            that.params.nextStepNo.split(",").forEach((item, i) => {
              that.nextStepData.push(
                item.split("_")[0] + "@0:" + res[i].depId + "_" + res[i].postId
              );
            });
            that.onGetNextCommit();
          } else {
            that.params.nextStepNo.split(",").forEach((item, i) => {
              that.nextStepData.push(
                item.split("_")[0] + "@0:" + res[i].depId + "_" + res[i].postId
              );
            });
            that.onGetNextCommit();
          }
        }
      );
    },
    // 提交
    onGetNextCommit() {
      const that = this;
      let items = [];
      that.tableData.forEach((item) => {
        let obj = {};
        obj.yarn4PlanId = item.id;
        obj.yarnId = item.yarnId;
        obj.weight = item.weight;
        obj.packageIds = item.packageIds;
        obj.yarnColor = item.yarnNo;
        obj.yarnName = item.yarnName;
        obj.yarnStrandard = item.yarnStandard + "/" + item.yarnStrandNum;
        items.push(JSON.stringify(obj));
      });
      getNextCommit(
        {
          taskId: that.params.taskId,
          stepNo: that.params.stepNo,
          nextStepIndex: that.nextStepData.join(","),
          loopCount: "1",
          resId: that.params.resId,
          resParams: JSON.stringify({
            stepId: that.params.stepId,
            stepNo: that.params.stepNo,
            stepName: that.params.stepName,
            items: [{ opt: 2, label: "data", value: JSON.stringify(items) }],
          }),
        },
        function () {
          that.$toast({
            type: "success",
            message: "确认成功，下一步" + that.params.nextStepName,
            onClose: () => {
              // 跳转整经详情
              openWin("index");
            },
          });
        }
      );
    },
    // 接单
    onGetTaskAccept() {
      const that = this;
      let obj = {
        stepNo: 16,
        taskId: that.params.taskId,
        subResIds: that.subResIds,
        stepId: that.params.stepId,
      };
      // 打印
      getTaskAccept(obj, () => {
        that.onGetConnectState(true);
      });
    },
    // 获取重量
    onGetWeight() {
      const that = this;
      that.$toast.loading({
        message: "自动称重中",
        forbidClick: true,
        duration: 20000,
        loadingType: "spinner",
      });
      var serial = window.api.require("serialPort");
      serial.examine(function (ret) {
        if (ret.code) {
          serial.openRead(
            {
              com: "/dev/ttyS3", //串口地址
              rate: 9600, //波特率
              delay: 500, //RX延时 此参数能让数据返回完整单位毫秒（具体设置大小自测）
              hex: false, //返回数据类型 false:text  true:hex
            },
            function (ret) {
              if (ret.code && ret.data) {
                let respon = ret.data;
                serial.close(function (ret) {
                  that.$toast.clear();
                  let res = respon.split(" ");
                  let resultWeight = [...new Set(res)].filter(
                    (item) => item !== ""
                  )[0];
                  // 关闭协议成功
                  that.tableData[0].value = that.insert_flg(
                    resultWeight.trim(),
                    ".",
                    2
                  );
                  if (ret.code) {
                    // 关闭
                  }
                });
              }
            }
          );
        } else {
          that.$toast.clear();
          that.$toast.fail("协议打开失败，请手动填写重量");
        }
      });
    },
    // str表示原字符串变量，flg表示要插入的字符串，sn表示要插入的位置
    insert_flg(str, flg, sn) {
      var newstr = "";
      let frontStr = str.substr(0, str.length == 3 ? 1 : sn);
      let afterStr = str.substr(
        str.length == 3 ? 1 : sn,
        str.length == 3 ? sn : str.length - sn
      );
      newstr = frontStr + flg + afterStr;
      return newstr;
    },
  },
};
</script>

<style lang="scss">
.yarn {
  display: flex;
  flex-direction: column;
  .public-scroll {
    height: calc(100vh - 200px);
    .van-cell__title {
      flex: 0 0 80%;
      .yarn-cell {
        display: flex;
        justify-content: space-between;
        span {
          flex: 1;
          font-size: 20px;
          text-align: center;
        }
      }
    }
  }
  .van-icon-success::before {
    position: relative;
    top: 15px;
    font-size: 36px;
  }

  .van-dialog {
    width: 560px;
    height: 417px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .van-dialog__header {
      font-size: 36px;
      color: #333333;
      margin-top: 20px;
    }
    .van-dialog__content {
      font-size: 30px;
      color: #333333;
      text-align: center;
    }
    .van-dialog__footer {
      height: 80px;
      .van-button {
        height: 100%;
        font-size: 36px;
        color: #1677ff;
      }
    }
    .van-cell__title {
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }
    .van-cell__title,
    .van-cell__value {
      span {
        font-size: 26px;
      }
    }
    .van-cell-group {
      .van-cell {
        margin: 15px 0;
      }
    }
  }
  .yarn-btn {
    width: 700px;
    height: 100px;
    background: #1677ff;
    border-radius: 2px;
    font-size: 32px;
    color: #ffffff;
    margin: 0 auto;
    // margin-bottom: 100px;
  }
}
</style>
